package com.ehotting.edsta.circuitDesign.gen.circuit.script;

import com.ehotting.edsta.circuitDesign.domain.EsRuleScript;
import com.ehotting.edsta.circuitDesign.gen.ScriptConstants;
import com.ehotting.edsta.circuitDesign.gen.element.bean.ConditionBean;
import com.ehotting.edsta.circuitDesign.gen.element.enums.ConditionTypeEnum;
import com.ehotting.edsta.circuitDesign.gen.element.enums.ScriptTypeEnum;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ConditionCircuitScript extends CircuitScriptAbstract {

    @Override
    public String invoke(EsRuleScript esScript, List<String> argumentsList, String functionName) {
        StringBuffer buf = new StringBuffer();
        buf.append(functionStart( functionName, argumentsList));
        buf.append(execute( esScript));
        buf.append(functionEnd());
        return buf.toString();
    }

    protected String execute(EsRuleScript esScript){
        StringBuffer buf = new StringBuffer();
        List<ConditionBean> conditionList = setConditionOrder(esScript);
        buf.append(defineIfBody(conditionList));
        return buf.toString();
    }

    /***
     * 定义子方法体
     * @param conditionList
     * @return
     */
    private String defineIfBody(List<ConditionBean> conditionList){
        StringBuffer buf = new StringBuffer();
        buf.append(ScriptConstants.TAB);
        for(ConditionBean conditionBean : conditionList){
            ConditionTypeEnum cType = ConditionTypeEnum.getObject(conditionBean.getConditionType());
            /**定义 if、else if、else语句**/
            buf.append(cType.getScript());
            if(cType == ConditionTypeEnum.IF || cType == ConditionTypeEnum.ELSE_IF) {
                buf.append("(!(").append(conditionBean.getConditionScript()).append("))");
            }
            /**定义执行语句**/
            buf.append("{").append(ScriptConstants.LINE);

            buf.append(ScriptConstants.TAB(2));
            buf.append("return false;").append(ScriptConstants.LINE);
            buf.append(ScriptConstants.TAB).append("}");
        }
        buf.append(ScriptConstants.LINE);
        buf.append(ScriptConstants.TAB).append("return true;");
        buf.append(ScriptConstants.LINE);

        return buf.toString();
    }


    @Override
    public boolean isTrue(ScriptTypeEnum code){
        return ScriptTypeEnum.CONDITION == code;
    }

    @Override
    public String getExample() {
        return null;
    }
}
